class MainController < ApplicationController
  layout 'default'
  
  # Será renderizado apenas a view index.rhtml
  def index
    @lasted_videos = get_lasted_videos
    #puts @lasted_videos.inspect
    
    @download_queue = get_download_queue
    puts @download_queue.inspect
  end
  
  # Solicitar o download de um video
  def get_video
    #print params[:option]
    sleep 3
    jf = Job.new
    send_attachment = (params[:option] = 1) ? true : false
    v = Video.find_by_url(params[:url])
    
    if not v.nil?
      cj = CompletedJob.find_by_video_id(v.id)
      if not cj.nil? 
        jf.send_email(params[:url], params[:email], send_attachment)
        @msg_status = "O video solicitado já está diponível imediatamente.<br>" + link_download(v.id)
      else
        jf.add_notification(params[:url], params[:email], send_attachment)
        @msg_status = "O video solicitado já está na fila de downloads.<br>Você receberá um e-mail quando estiver pronto."
      end
    else
      jf.create(params[:url], params[:email], send_attachment)
      @msg_status = "Seu link foi adicionado na fila de downloads.<br>Você receberá o e-mail quando estiver pronto"
    end
    render :partial => 'status'
    
  end

  private
  # Obter videos mais baixados
  def get_lasted_videos(limit=10)
    Video.find(:all,
      :select => "video.id, url, filename, title, count(*) as total",
      :joins => "INNER JOIN completed_job cb ON cb.video_id = video.id",
      :group => "video.id, url, filename, title",
      :order => "count(*) DESC",
      :limit => limit)
  end

  # Obter os downloads na fila
  def get_download_queue(limit=10)
    Video.find(:all,
      :select => "video.id, url, filename, title, count(*) as total",
      :joins => "INNER JOIN completed_job cb ON cb.video_id = video.id",
      :group => "video.id, url, filename, title",
      :order => "count(*) DESC",
      :limit => limit)    
  end
  
  def link_download(video_id)
    v = Video.find_by_id(video_id)
    if not v.nil?
      '/files/' + v.filename
    else
      nil
    end
  end  
  
end
